import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';
import 'package:flutter_enjoy_plus/utils/eventBus.dart';

import 'mine/index.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({Key? key}) : super(key: key);

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  final List _tabs = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png',
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png',
    }
  ];
  // 底部tabbar选中的索引
  int _index = 0;

  updateIndex(int index) {
    setState(() {
      _index = index;
    });
  }
  // 第一种方案 --> 通过index来判断显示哪个页面
  // getTabbar() {
  //   if (_index == 0) {
  //     return const HomePage();
  //   } else if (_index == 1) {
  //     return const MinePage();
  //   }
  // }
  // 第二种方案 -> (性能更优) IndexStacked -> 通过index 指定渲染 (不会每次都销毁重建)

  // 封装 获取底部TabsItem 内容
  List<BottomNavigationBarItem> getTabbarContent() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabs) {
      list.add(BottomNavigationBarItem(
        icon: Image.asset(item['icon']!, width: 30, height: 30),
        activeIcon: Image.asset(item['activeIcon']!, width: 30, height: 30),
        label: item['label'],
      ));
    }
    return list;
  }

  @override
  @override
  void initState() {
    super.initState();
    // 初始化token
    tokenManager.init();
    // 订阅事件
    eventBus.on<logoutEvent>().listen((event) {
      // 跳转到登录页
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    // 脚手架
    return Scaffold(
      // SafeArea 安全区组件
      body: SafeArea(
          child: IndexedStack(index: _index, children: [
        const HomePage(),
        MinePage(currentIndex: _index, updateIndex: updateIndex)
      ])),
      // 底部的tabbar
      bottomNavigationBar: BottomNavigationBar(
          backgroundColor: const Color.fromRGBO(255, 247, 254, 1),
          items: getTabbarContent(),
          selectedItemColor: const Color.fromRGBO(86, 148, 177, 1),
          unselectedItemColor: const Color.fromRGBO(8, 6, 7, 1),
          type: BottomNavigationBarType.fixed,
          currentIndex: _index,
          onTap: (int index) {
            setState(() {
              _index = index;
            });
          }),
    );
  }
}
